package com.atguigu.tingshu.album.service.impl;



import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadApiService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Component
public class FileUploadApiServiceImpl implements FileUploadApiService {

    @Autowired
    MinioConstantProperties minioConstantProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            String urls = "";
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpoint() + ":" + minioConstantProperties.getPort())
                            .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecretKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder()
                            .bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {

                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioConstantProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket("asiatrip")
//                            .object("asiaphotos-2015.zip")
//                            .filename("/home/user/Photos/asiaphotos.zip")
//                            .build());

            InputStream inputStream = file.getInputStream();
            PutObjectArgs.Builder builder = PutObjectArgs.builder();
            PutObjectArgs test = builder
                    .stream(inputStream, inputStream.available(), -1)
                    .bucket(minioConstantProperties.getBucketName())
                    .object(filename)
                    .build();
            minioClient.putObject(test);

            urls = minioConstantProperties.getEndpoint() + ":" + minioConstantProperties.getPort() + "/"
                    + minioConstantProperties.getBucketName() + "/" + filename;
            return urls;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
            throw  new GuiguException(201,"上传失败");
        }
    }
}
